<template name='sunui-upimg'>
	<scroll-view scroll-x class="sunui-uploader-files">
		<view class="picList" :style="'width:'+upload_img_wh+'rpx;height:'+upload_img_wh+'rpx;'" @click="joinPicture" v-if="isShow">
			<image src="/static/images/icon/add.png" :style="'width:'+upload_img_wh+'rpx;height:'+upload_img_wh+'rpx;'"></image>
		</view>
		<view class="picList" v-for="(item,index) in upload_before_list" :key="index" :style="'width:'+upload_img_wh+'rpx;height:'+upload_img_wh+'rpx;'" @click="previewImage(index)">
			<image :style="'width:'+upload_img_wh+'rpx;height:'+upload_img_wh+'rpx;'" :src="item.path" class="uploadImg"></image>
			<image src="/static/images/icon/deltel.png" class="deltel right" @click.stop="removeImage(index)" v-show="upimg_move"></image>
			<!-- <view class="sunui-loader-filecontent" v-if="item.upload_percent<100">{{item.upload_percent}}%</view> -->
		</view>
	</scroll-view>
</template>

<script>
	import util from '@/common/util.js'
	export default {
		data() {
			return {
				// 上传图片格式限制
				upload_format: ['jpg', 'jpeg', 'png'],
				// 选择图片tempFile
				upload_cache: [],
				// 预览数组->支持从服务器拉取
				upload_cache_list: [],
				// 上传数组
				upload_before_list: [],
				// 图片大小
				upload_img_size: [],
				// 超出限制数组
				upload_exceeded_list: [],
				// 最大上传容量(M)
				upload_max: 10,
				// 图片/选择宽高
				upload_img_wh: 168,
				// 测试接口(建议七牛、阿里云、腾讯云都采用后端对接，直接调用后端上传)
				url: this.global.apiUrl + '/oss_upload'
			}
		},
		name: 'sunui-upimg',
		props: {
			upload_auto: {
				type: Boolean,
				default: true
			},
			upimg_move: {
				type: Boolean,
				default: true
			},
			upload_count: {
				type: [String,Number],
				default: 1
			},
			product_id: {
				type: [String,Number],
				default: 0
			}
		},
		created() {
			// _self = this;
		},
		computed: {
			isShow(){
				if(this.upload_count == 1){
					if(this.upload_before_list.length != 0 && this.upload_cache_list.length != 0){
						return false
					}else if(this.upload_before_list.length == 0 && this.upload_cache_list.length == 0){
						return true
					}
				}
				return true
			}
		},
		mounted() {
			let _self = this;
			_self.$nextTick(function() {
				_self.upload_before_list.map(function(item) {
					_self.upload_cache_list.push(item.path);
				});
				// _self.upimg_move = true;
				_self.emit();
			})
		},
		methods: {
			upImage(paths) {
				let _self = this;
				const promises = paths.map((path) => {
					return promisify(upload)({
						url: _self.url,
						path: path,
						name: 'file',
						extra: {},
					})
				})

				uni.showLoading({
					title: `正在上传...`,
				});

				Promise.all(promises).then((data) => {
					console.log(data)
					uni.hideLoading();
					_self.upload_cache_list.push(...data);
					_self.emit();
				}).catch((res) => {
					console.log(res);
					uni.hideLoading();
				});
			},
			joinPicture(){
			    var that = this;
			    if (that.upload_before_list >= that.upload_count) {
			      util.showModal('提示','最多上传'+ that.upload_count +'张图片')
			      return;
			    }
			    uni.showActionSheet({
					itemList: ["从相册中选择", "拍照"],
					itemColor: "#f7982a",
					success: function (res) {
						if (!res.cancel) {
							if (res.tapIndex == 0) {
								that.chooseImage("album");
							} else if (res.tapIndex == 1) {
								that.chooseImage("camera");
							}
						}		
					}
			    })
			},
			chooseImage(type) {
				let _self = this;
				uni.chooseImage({
					count: _self.upload_count,
					sizeType: ['compressed', 'original'],
					sourceType: [type],
					success: async (res) => {
						for (let i = 0, len = res.tempFiles.length; i < len; i++) {
							// res.tempFiles[i]['upload_percent'] = 0;
							// h5暂时不能获取图片格式,只支持其它平台
							// #ifdef H5
							await uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: async function(image) {
									if ((Math.ceil(res.tempFiles[i].size / 1024) < _self.upload_max * 1024)) {
										await _self.upload_before_list.push(res.tempFiles[i]);
									} else {
										uni.showToast({
											title: `已过滤超出限制的图片`,
											icon: 'none'
										});
									}
								}
							});
							// #endif
							// #ifndef H5
							await uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: async function(image) {
									let reg = new RegExp("" + image.type);
									let formart = _self.upload_format.join(',');
									if ((Math.ceil(res.tempFiles[i].size / 1024) < _self.upload_max * 1024) && reg.test(formart)) {
										await _self.upload_before_list.push(res.tempFiles[i]);
									} else {
										uni.showToast({
											title: `已过滤超出限制的图片`,
											icon: 'none'
										});
									}
								}
							});
							// #endif
						}
						// TODO.暂未解决文件格式过滤
						_self.upload_cache = await res.tempFilePaths;
						_self.upload(_self.upload_auto);
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			async upload(upload_auto) {
				console.log(upload_auto)
				let _self = this;
				upload_auto ? await _self.upImage(_self.upload_cache) : console.warn(
					`传输参数:this.$refs.xx.upload(true)才可上传,默认false`);
			},
			previewImage(idx) {
				let _self = this;
				uni.previewImage({
					current: idx,
					urls: _self.upload_cache_list
				});
			},
			removeImage(idx) {
				let _self = this;
				_self.upload_before_list.splice(idx, 1);
				_self.upload_cache_list.splice(idx, 1);
				_self.emit();
			},
			emit() {
				let _self = this;
				// console.log(this.product_id);
				if(this.product_id != 0){
					_self.$emit('change', _self.upload_cache_list,this.product_id);
				}else{
					_self.$emit('change', _self.upload_cache_list);
				}
				
			}
		}
	}


	const promisify = (api) => {
		return (options, ...params) => {
			return new Promise((resolve, reject) => {
				api(Object.assign({}, options, {
					success: resolve,
					fail: reject
				}), ...params);
			});
		}
	}

	const upload = options => {
		// console.log(options)
		var url = options.url,
			path = options.path,
			name = options.name,
			// data = options.data,
			extra = options.extra,
			success = options.success,
			progress = options.progress,
			fail = options.fail
			
		const uploadTask = uni.uploadFile({
			url: url,
			filePath: path,
			name: name,
			formData: extra,
			success: function(res) {
				console.log(res)
				var data = res.data
				try {
					//Tip : 切记->主要修改这里图片的返回值为真实返回路径!!! 详情见示例
					// data = JSON.parse(res.data).info;
				} catch (e) {
					throw (e, data)
				}
				// 根据自己的返回数据做相应判断,服务器返回200即代表成功请求
				if (res.statusCode == 200) {
					if (success) {
						success(data)
					}
				} else {
					if (fail) {
						fail(data)
					}
				}

			},
			fail: function(res) {
				console.log(res)
				if (fail) {
					fail(res)
				}
			}
		})
		// uploadTask.onProgressUpdate(async function(res) {
		// 	for (let i = 0, len = _self.upload_before_list.length; i < len; i++) {
		// 		_self.upload_before_list[i]['upload_percent'] = await res.progress;
		// 	}
		// 	_self.upload_before_list = _self.upload_before_list;
		// });
	}
</script>

<style lang="scss">
	.sunui-uploader-files {
		@include width;
		overflow:hidden;
		white-space: nowrap;
		.picList{
			@include margin(30rpx,'left');
		    position: relative;
		    display: inline-block;
			&:first-child{
				@include margin(35rpx,'top');
			}
			.uploadImg{
				@include borderR(10rpx);
				@include border(2rpx,$borderBg);
			}
			.deltel{
			    position: absolute;
				@include widthHeight(30rpx);
				&.right{
					right:-15rpx;
					top:-15rpx;
				}
			}
		}
	}
</style>
